<?php

namespace App\Http\Controllers;

use http\Env\Response;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class UserController extends Controller
{
    /**
     * @param Request $request
     * @return void
     */
    public function userAdd(Request $request)
    {
        $validatedData = $request->validate([
            'avatar' => 'required',
            'dept' => 'required',
            'group' => 'required',
            'id' => 'nullable',
            'name' => 'required',
            'password' => 'nullable',
            'userName' => 'required',
        ]);
        $roles = $validatedData['group'];
        unset($validatedData['group']);
        if (empty($validatedData['id'])) { //新增
            // 验证有无重复name
            $existingUser = User::where(['name' => $validatedData['name']])->first();
            if ($existingUser) {
                return response()->json(['code' => 400, 'message' => '用户名已存在']);
            }
            $validatedData['password'] = Hash::make($validatedData['password']);
            $user = User::create($validatedData);
        } else { //更新
            $user = User::findOrFail($validatedData['id']);
            unset($validatedData['password']);
            $user->update($validatedData);
        }
        // 分配角色
        $user->syncRoles($roles);
        return response()->json(['code' => 200, 'message' => '成功', 'data' => $user->id]);
    }

    /**
     * @param Request $request
     * @return void
     */
    public function userIndex(Request $request)
    {
//        DB::listen(function ($query) {
//            Log::info($query->sql);
//            Log::info($query->bindings);
//            Log::info($query->time);
//        });
        $validatedData = $request->validate([
            'page' => 'nullable|integer',
            'pageSize' => 'nullable|integer',
            'name' => 'nullable',
            'dept' => 'nullable|integer', // 前端传来的部门 ID 是整数
        ]);
        $pageSize = $validatedData['pageSize'] ?? 20; // 默认每页20条记录
        $users = User::when(isset($validatedData['name']), function ($query) use ($validatedData) {
            return $query->where('name', 'like', '%' . $validatedData['name'] . '%');
        })
        ->when(isset($validatedData['dept']), function ($query) use ($validatedData) {
            return $query->whereJsonContains('dept', intval($validatedData['dept']));
        })
        ->paginate($pageSize);
        $data = [
            'page' => $users->currentPage(),
            'pageSize' => intval($users->perPage()),
            'rows' => $users->items(),
            'total' => $users->total(),
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function userDel($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $menu = User::findOrFail($num);
                $menu->delete();
            }
        } else {
            $menu = User::findOrFail($ids);
            $menu->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }
}
